#!/bin/sh /etc/rc.common

USE_PROCD=1
START=99
STOP=10

PROG=/usr/share/mt5700webui/server.py
CONFIG=/etc/config/mt5700webui
PID_FILE="/var/run/mt5700webui.pid"

start_service() {
    local delay=0
    
    # 检查是否是通过开机启动调用
    if [ "$INIT" = "boot" ]; then
        # 获取开机启动的延时设置
        delay=$(uci -q get mt5700webui.main.delay || echo 30)
    fi
    
    procd_open_instance
    if [ $delay -gt 0 ]; then
        # 开机启动时使用延时
        procd_set_param command /bin/sh -c "sleep $delay && exec /usr/bin/python3 $PROG"
    else
        # 手动启动时立即执行
        procd_set_param command /usr/bin/python3 $PROG
    fi
    procd_set_param pidfile "$PID_FILE"
    procd_set_param respawn
    procd_set_param stdout 1
    procd_set_param stderr 1
    procd_set_param user root
    procd_set_param cwd /usr/share/mt5700webui
    procd_close_instance
}

stop_service() {
    # 使用PID文件停止服务
    if [ -f "$PID_FILE" ]; then
        local pid=$(cat "$PID_FILE")
        kill $pid >/dev/null 2>&1
        rm -f "$PID_FILE"
    fi
    
    # 额外检查确保进程终止
    pids=$(pgrep -f "python3 /usr/share/mt5700webui/server.py")
    [ -n "$pids" ] && kill $pids
}

service_running() {
    # 使用PID文件检查服务状态
    if [ -f "$PID_FILE" ]; then
        local pid=$(cat "$PID_FILE")
        if [ -d "/proc/$pid" ]; then
            return 0
        fi
    fi
    return 1
}

status() {
    # 使用PID文件提供准确状态
    if service_running; then
        echo "Service is running"
        return 0
    else
        echo "Service is not running"
        return 1
    fi
}

restart() {
    stop_service
    sleep 5
    start_service
}